import 'package:e_reception_flutter/ui/punch_in_rule/punch_in_rule_list_widget.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'dart:math' as Math;

class PunchInRuleBean extends ChangeNotifier {
  ///上班弹性时间开关
  bool _onDutyTimeCheck;

  ///上班时间弹性时长 秒
  int _onDutyFlexibleTime;

  /// 上班时间
  String _onDutyTime;

  ///下班弹性时间开关
  bool _offDutyTimeCheck;

  ///下班时间弹性时长
  int _offDutyFlexibleTime;

  /// 下班时间
  String _offDutyTime;

  ///时长要求
  int _duration;

  ///自定义的规则命名
  String _name;

  ///开启时长要求
  bool _durationEnable;

  ///类型 see[PunchInRuleType]
  PunchInRuleType type;

  ///适用对象
  List<String> _suitableObjectIds;

  String id;

  ///当前角色类型
  String roleType;

  String delflg;

  ///是否覆盖，默认不覆盖
  bool cover;

  ///待覆盖的id
  String coverid;

  ///选择的部门
  String department;

  ///选择的部门id
  String departmentId;

  ///选择的部门
  String classname;

  ///选择的班级id
  String classId;

  ///适用对象id
  List<String> get suitableObjectIds => _suitableObjectIds;

  ///适用对象名
  String suitableObjectName;

  PunchInRuleBean([this.type, this.roleType]);

  set suitableObjectIds(List<String> value) {
    _suitableObjectIds = value;
    notifyListeners();
  }

  bool get durationEnable => _durationEnable;

  set durationEnable(bool value) {
    _durationEnable = value;
    notifyListeners();
  }

  String get onDutyTime => _onDutyTime;

  set onDutyTime(String value) {
    //上班时间晚于下班时间，不记录
    if (value != null &&
        _offDutyTime != null &&
        value.compareTo(_offDutyTime) > 0) {
      return;
    }
    _onDutyTime = StringUtils.isEmpty(value) ? null : value;
    notifyListeners();
  }

  bool get onDutyTimeCheck => _onDutyTimeCheck;

  set onDutyTimeCheck(bool value) {
    _onDutyTimeCheck = value;
    notifyListeners();
  }

  int get onDutyFlexibleTime => _onDutyFlexibleTime;

  set onDutyFlexibleTime(int value) {
    _onDutyFlexibleTime = value;
    notifyListeners();
  }

  bool get offDutyTimeCheck => _offDutyTimeCheck;

  set offDutyTimeCheck(bool value) {
    _offDutyTimeCheck = value;
    notifyListeners();
  }

  int get offDutyFlexibleTime => _offDutyFlexibleTime;

  set offDutyFlexibleTime(int value) {
    _offDutyFlexibleTime = value;
    notifyListeners();
  }

  String get offDutyTime => _offDutyTime;

  set offDutyTime(String value) {
    _offDutyTime = StringUtils.isEmpty(value) ? null : value;
    // if (_onDutyTime != null && _duration == null) {
    //   _duration = _offDutyTime - _onDutyTime;
    // }
    notifyListeners();
  }

  int get duration => _duration;

  set duration(int value) {
    _duration = value;
    notifyListeners();
  }

  String get name => _name;

  set name(String value) {
    _name = value;
    notifyListeners();
  }

  ///时间秒转字符串
  static String getFormatTime(int timeSecond) {
    if (timeSecond == null) {
      return null;
    }
    return DateUtil.formatDateMs(timeSecond * 1000, format: "HH:mm");
  }

  ///时长要求 时间秒转字符串  （点击默认值直接弹起选择器更改：7.5小时、8小时、8.5小时……12小时。（只能选我们提供的选项，关闭后会复默认值）
  static String formatDurationTimeString(int sub) {
    if (sub == null) {
      return null;
    }
    if (sub == null || sub < 0) {
      return null;
    }
    int hour = ((sub) / 3600).floor();
    int minute = ((sub - (hour * 3600 ))  / 60).floor();

    if ((hour == null || hour <= 0) && (minute == null || minute <= 0)) {
      return null;
    }
    if (hour == null || hour <= 0) {
      if (minute <= 1) {
        return "1分钟";
      }
      return "$minute分钟";
    }
    if (minute <= 0) {
      return "$hour小时";
    }
    return "$hour小时$minute分钟";
  }

  ///时间字符 转datetime
  static DateTime getFormatDateTime(String timeSecond) {
    if (StringUtils.isEmpty(timeSecond)) {
      return null;
    }
    String today = DateUtil.formatDate(DateTime.now(), format: 'yyyy-MM-dd');
    return DateTime.parse('$today $timeSecond:00');
  }

  ///时间字符 HH:mm 格式 转datetime 5分钟间隔
  /// plus5min 加5分钟 minus5 减5分钟
  static DateTime getFormatDateTime5min(String timeSecond,{bool plus5min,bool minus5Min}) {
    if (StringUtils.isEmpty(timeSecond)) {
      return null;
    }
    String today = DateUtil.formatDate(DateTime.now(), format: 'yyyy-MM-dd');
    if (timeSecond.contains(':')) {
      String hour = timeSecond.split(':')[0];
      String minute = timeSecond.split(':')[1];
      if(minute.startsWith('0')){
        minute = minute.substring(1, 2);
      }
      int minuteInt = int.parse(minute);
      if (minuteInt % 5 > 0) {
        //说明不是5结尾
        minuteInt = (minuteInt / 5).round() * 5;
      }
      if (minuteInt < 10) {
        minute = '0${minuteInt.toString()}';
      }else{
        minute=minuteInt.toString();
      }
      timeSecond='$hour:$minute';
    }
    DateTime time=  DateTime.parse('$today $timeSecond:00');
    if(plus5min??false){
      time=time.add(Duration(minutes: 5));
    }
    if(minus5Min??false){
      time= time.subtract(Duration(minutes: 5));
    }
    return time;
  }

  ///datetime 转秒
  static String getDateTimeToSecond(DateTime dateTime) {
    if (dateTime == null) {
      return null;
    }
    return DateUtil.formatDate(dateTime, format: "HH:mm");
  }

  ///是否可以提交
  ///上班时间、下班时间、时长要求中有一项设置了即算生效
  bool canCommit() {
    return StringUtils.isNotEmpty(_onDutyTime) ||
        StringUtils.isNotEmpty(_offDutyTime) ||
        (_duration ?? 0) > 0;
  }

  ///设置时长的要求默认值
  String getDefaultDuration() {
    // if (_duration != null) {
    //   return formatDurationTimeString(_duration) ?? "请设置";
    // }
    if (StringUtils.isNotEmpty(_offDutyTime) &&
        StringUtils.isNotEmpty(_onDutyTime)) {
      int duration = getFormatDateTime(_offDutyTime).millisecondsSinceEpoch -
          getFormatDateTime(_onDutyTime).millisecondsSinceEpoch;
      // if (duration < 60 * 1000 * 60 * 7.5) {
      //   duration = (8.5 * 60 * 60 * 1000).toInt();
      // }
      // if (duration > 60 * 1000 * 60 * 12) {
      //   duration = (8.5 * 60 * 60 * 1000).toInt();
      // }
      if(duration<=0){
        return "请设置";
      }
      return formatDurationTimeString(duration~/1000) ?? "请设置";
    } else {
      return "请设置";
    }
  }

  ///设置时长的要求默认值
  void setDefaultDurationValue() {
    if (_offDutyTime != null && _onDutyTime != null) {
      _duration = getFormatDateTime(_offDutyTime).millisecondsSinceEpoch -
          getFormatDateTime(_onDutyTime).millisecondsSinceEpoch;
      _duration=_duration~/1000;
      // if (_duration < 60  * 60 * 7.5) {
      //   _duration = (8.5 * 60 * 60 ).toInt();
      // }
      // if (_duration > 60  * 60 * 12) {
      //   _duration = (12 * 60 * 60 ).toInt();
      // }
    } else {
      _duration = (8.5 * 60 * 60 ).toInt();
    }
  }

  @override
  String toString() {
    return '{_onDutyTimeCheck: $_onDutyTimeCheck, _onDutyFlexibleTime: $_onDutyFlexibleTime, _onDutyTime: $_onDutyTime, _offDutyTimeCheck: $_offDutyTimeCheck, _offDutyFlexibleTime: $_offDutyFlexibleTime, _offDutyTime: $_offDutyTime, _duration: $_duration, _name: $_name, _durationEnable: $_durationEnable, type: $type, _suitableObjectIds: $_suitableObjectIds}';
  }

  static PunchInRuleBean fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    PunchInRuleBean attRuleListBean = PunchInRuleBean();
    attRuleListBean.delflg = map['delflg'];
    attRuleListBean.id = map['arid'];
    attRuleListBean.roleType = map['groupType'];
    attRuleListBean.name = map['ruleName'];
    attRuleListBean.onDutyTime = map['dutytime'];
    attRuleListBean.offDutyTime = map['offdutytime'];
    attRuleListBean.onDutyFlexibleTime = map['onFlextime'];
    attRuleListBean.offDutyFlexibleTime = map['offFlextime'];
    attRuleListBean.duration = map['duration'];
    //如果弹性是0，则表示未设置
    if ((attRuleListBean.duration ?? 0) > 0) {
      attRuleListBean.durationEnable = true;
    } else {
      attRuleListBean.durationEnable = false;
      attRuleListBean.duration = null;
    }
    if ((attRuleListBean.onDutyFlexibleTime ?? 0) == 0) {
      attRuleListBean.onDutyFlexibleTime = null;
      attRuleListBean.onDutyTimeCheck = false;
    } else {
      attRuleListBean.onDutyTimeCheck = true;
    }
    if ((attRuleListBean.offDutyFlexibleTime ?? 0) == 0) {
      attRuleListBean.offDutyFlexibleTime = null;
      attRuleListBean.offDutyTimeCheck = false;
    } else {
      attRuleListBean.offDutyTimeCheck = true;
    }
    attRuleListBean.type = fromPunchInRuleTypeString(map['type']);
    attRuleListBean.department = map['department'];
    attRuleListBean.departmentId = map['departmentids'];
    attRuleListBean.classname = map['classname'];
    attRuleListBean.classId = map['classId'];
    if (attRuleListBean.roleType == PunchInRuleListWidget.TYPE_STU) {
      attRuleListBean.suitableObjectIds = attRuleListBean.classId?.split(',');
      attRuleListBean.suitableObjectName =
          attRuleListBean.classname?.replaceAll(',', '、');
    } else {
      attRuleListBean.suitableObjectIds =
          attRuleListBean.departmentId?.split(',');
      attRuleListBean.suitableObjectName =
          attRuleListBean.department?.replaceAll(',', '、');
    }

    return attRuleListBean;
  }

  Map toJson() => {
        "duration": duration,
        "delflg": delflg,
        "arid": id,
        "groupType": roleType,
        "onFlextime": onDutyFlexibleTime,
        "ruleName": name,
        "offFlextime": offDutyFlexibleTime,
        "dutytime": _onDutyTime,
        "offdutytime": offDutyTime,
        "arid": id,
        "type": type == PunchInRuleType.general ? '00' : '01',
        'department': department,
        'departmentids': departmentId,
        'classname': classname,
        'classId': classId,
      };

  ///考勤规则类型
  static PunchInRuleType fromPunchInRuleTypeString(String str) {
    if (str == "00") {
      return PunchInRuleType.general;
    }
    return PunchInRuleType.custom;
  }

  ///是否是通用类型
  bool isGeneral() {
    return type == PunchInRuleType.general;
  }
}

///打卡类型
enum PunchInRuleType {
  ///通用
  general,

  ///自定义
  custom
}
